#ifndef _MIX_THREAD_THREAD_H_
#define _MIX_THREAD_THREAD_H_

#include <string>
#ifdef _MSC_VER
#include <functional>
#else
#include <tr1/functional>
#endif

namespace mix
{

class Thread
{
public:
    typedef std::tr1::function<void ()> ThreadFunc;
    
	enum State
	{
		New,
		Running,
		Blocked,
		Waiting,
		Terminated,
	};

	Thread( const std::string& name="");
	Thread( const ThreadFunc& threadFunc, const std::string& name="");
    virtual ~Thread();

	State getState() const;
	//int64_t getId() const;
	const std::string& name() const;

	bool setThreadFunc( const ThreadFunc& func);
	template< typename T>
	bool setThreadFunc( T& functor);
	
	bool start();
	bool join();
    bool detach();

    void* getNative();

    static void exit( int code);
    static void yield();
    static void sleep( long msec);
    
private:
    Thread( const Thread&);
    Thread& operator=( const Thread&);

    void run();
    friend void callThreadRun( Thread*);

private:
	volatile State _state;
	ThreadFunc _threadFunc;
	std::string _name;

    void* _impl;

	template< typename T>
	class Functor2ThreadFunc
	{
		T& m_functor;
	public:
		Functor2ThreadFunc( T& t)	: m_functor( t) {
		}
    };
		
};

}	// namespace mix

#endif	// _MIX_THREAD_THREAD_H_
